package com.fingard.dsp.bank.directbank.tfb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class TFB01SinglePay extends TFB01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail = Transfer(p_req1908);

        if ("-1".equals(tmpRetDetail.respCode) && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    //跨行转账
    private RetAtsSglDetail Transfer(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        TFB01Header header = new TFB01Header();
        header.bsnCode = "Transfer";
        header.msgType = "trade";
        header.serialNo = p_req1908.singleDetail.askNumber;
        Connection conn = FGBiz.getLocalDbConn();
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader(xmlWriter, header);
        xmlWriter.writeStartElement("map");
        //大写，此处填 YQ）+当前年月日（6 位）+单据编号（4位，不足补 0
        xmlWriter.writeElementString("billCode", p_req1908.singleDetail.askNumber);
        xmlWriter.writeElementString("voucherType", "1");
        xmlWriter.writeElementString("payerAccNo", p_req1908.singleDetail.payAct);
        xmlWriter.writeElementString("payerAccName", p_req1908.singleDetail.payName);
        xmlWriter.writeElementString("payerOpenBranchName", p_req1908.singleDetail.payBankName);
        xmlWriter.writeElementString("payerProv", "");
        xmlWriter.writeElementString("payerCity", "");
        xmlWriter.writeElementString("payeeProv", "");
        xmlWriter.writeElementString("payeeCity", "");
        xmlWriter.writeElementString("remark", "");
        xmlWriter.writeElementString("usefor", "");
        xmlWriter.writeElementString("difAreaFlag", "");

        xmlWriter.writeElementString("payeeAccNo", p_req1908.singleDetail.recAct);
        xmlWriter.writeElementString("payeeAccName", p_req1908.singleDetail.recName);
        xmlWriter.writeElementString("payeeOpenBranchName", p_req1908.singleDetail.recBankName);
        xmlWriter.writeElementString("payeeBankNo", p_req1908.singleDetail.cnapsCode);

        xmlWriter.writeElementString("amt", p_req1908.singleDetail.payAmount);
        //

        xmlWriter.writeElementString("difBankFlag", p_req1908.singleDetail.sameBnk.equals("1") ? "0" : "1");
        xmlWriter.writeElementString("urgencyFlag", p_req1908.singleDetail.paySpd);
        xmlWriter.writeElementString("privateFlag", p_req1908.singleDetail.isPrivate);
        //余额支付
        xmlWriter.writeElementString("balanceFlag", "1");
        xmlWriter.writeElementString("cur", this.getBankConfig().getMapValueByKey("currencyMapping", p_req1908.singleDetail.payCur));
        xmlWriter.writeElementString("urgentLevel", "4");
        xmlWriter.writeElementString("postScript", p_req1908.singleDetail.purpose);
        xmlWriter.writeEndDocument();
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //银行返回出错  特殊处理
            if (tmpStrRet[1] != null && tmpStrRet[1].contains("< /msgType>")) {
                tmpStrRet[1] = tmpStrRet[1].replace("< /msgType>", "</msgType>");
            }
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String respondCode = tmpBkReader.getFirstText("/body/head/retCode");
                String respondInfo = tmpBkReader.getFirstText("/body/head/retMsg");
                if (respondCode!=null) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = respondInfo;
                    retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                    retDetail.transState = p_req1908.reqHeader.commandCode + respondCode + respondCode;
                    retDetail.payInfoCode = retDetail.transState;
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req1908.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1908.reqHeader.reqSeqID, tmpBkReader.getFirstText("/resRoot/appBody/streamNumber")});
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = respondInfo;
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    //状态查询
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        try {
            Connection conn = FGBiz.getLocalDbConn();
            TFB01Header header = new TFB01Header();
            header.bsnCode = "QueryTransfer";
            header.msgType = "query";
            header.serialNo = p_req1944.reqHeader.transSeqID;
            Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req1944.reqHeader.reqSeqID, p_req1944.reqHeader.bankCode});
            if (selMap != null && selMap.size() > 0) {
                p_req1944.reqHeader.transSeqID = selMap.get("BANKREQSEQID").toString();
                WriteBankLogLn("映射核心流水号为：" + p_req1944.reqHeader.transSeqID);
            } else {
                retAts.writeRespInfo("未找到对应的查询流水号，请确认支付请求是否通过");
                retAts.writeRespCode("-1");
                return retAts;
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, header);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeStartElement("map");
            xmlWriter.writeElementString("billCode", p_req1944.askNumber);
            xmlWriter.writeElementString("queryNum", "20");
            if (header.bsnCode.equals("41004002")) {
                xmlWriter.writeElementString("bankUserNo", p_req1944.reqHeader.transSeqID);
            } else {
                xmlWriter.writeElementString("streamNumber", p_req1944.reqHeader.transSeqID);
            }
            xmlWriter.writeEndDocument();
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String respondCode = tmpBkReader.getFirstText("/body/head/retCode");
                    String respondInfo = tmpBkReader.getFirstText("/body/head/retMsg");
                    //状态码不为空 根据映射来定义结果
                    if (StringHelper.hasAnyChar(respondCode)) {
                        retDetail.reqSeqID = p_req1944.askNumber;
                        retDetail.respCode = "0";
                        retDetail.respInfo = respondInfo;
                        retDetail.transState = p_req1944.reqHeader.commandCode + "+" + respondCode;
                        retDetail.payInfoCode = retDetail.transState;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = "未获取到银行返回信息，请再次查询";
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}